<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="渠道名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入渠道名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="SN码" prop="snCode">
        <el-input
          v-model="queryParams.snCode"
          placeholder="请输入SN码"
          clearable
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
        />
      </el-form-item>
      <el-form-item label="样本注册时间">
        <el-date-picker
          v-model="queryParams.beginCreateTime"
          value-format="yyyy-MM-dd"
          type="date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:tenant-package:create']">新增</el-button> -->
        <!-- <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        > -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增样本</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          >样本导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="importTemplate"
          :loading="exportLoading"
          >模版下载</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-bottom"
          size="mini"
          @click="handleUpload"
          >批量导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="mini"
          @click="handleSN"
          :loading="exportLoading"
          >样本回收</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="序号" type="index" />
      <el-table-column
        label="样本注册时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SN码" align="center" prop="snCode" />
      <el-table-column label="渠道名称" align="center" prop="tenantName" />
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="民族" align="center" prop="userNation" />
      <el-table-column label="身份证号" align="center" prop="userId" />
      <el-table-column label="联系电话" align="center" prop="userMobile" />
      <el-table-column
        label="样本回收时间"
        align="center"
        prop="receiveTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:tenant:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:tenant:delete']">删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <!-- 填写完成订单号的订单不可删除，也就是待发货的可删除，已发货的不可删除。
          to_deliver 未发货
          delivered 已发货
           -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.status == 'delivered' "
            @click="handleDelete(scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框(上传文件) -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xls, .xlsx"
        :auto-upload="false"
        drag
        :headers="upload.headers"
        :action="upload.url"
        :data="upload.data"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入 Excel 文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-col :span="24">
          <el-form-item label="所属项目" prop="projectId">
            <el-select
              v-model="form.projectId"
              placeholder="请选择所属项目"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in projectIdOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="SN码" prop="snCode">
            <el-input
              v-model="form.snCode"
              placeholder="请输入SN码"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入姓名"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="民族" prop="userNation">
            <el-input
              v-model="form.userNation"
              placeholder="请输入民族"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="身份证号" prop="userId">
            <el-input
              v-model="form.userId"
              placeholder="请输入身份证号"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="手机号" prop="userMobile">
            <el-input
              v-model="form.userMobile"
              placeholder="请输入手机号"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属渠道" prop="tenantId">
            <el-select
              v-model="form.tenantId"
              placeholder="请选择所属渠道"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in tenantIdOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 样本回收对话框(添加 / 修改) -->
    <el-dialog :title="titleSN" :visible.sync="openSN" width="800px">
      <el-form
        ref="formData"
        :model="formData"
        size="medium"
        label-width="150px"
      >
        <el-form-item
          label="样本编码"
          prop="snCodes"
          :rules="[
            { required: true, trigger: 'blur', message: '请输入样本编码' },
          ]"
        >
          <el-input
            v-model="formData.snCodes"
            type="textarea"
            placeholder="请输入样本编码,多条数据请已英文逗号隔开。如:hpv001,hpv002"
            :autosize="{ minRows: 4, maxRows: 4 }"
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchSN"
          >查询样本</el-button
        >
      </el-form>
      <p>样本信息</p>
      <template>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="序号"> </el-table-column>
          <el-table-column
            label="样本注册时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="snCode" label="SN码"> </el-table-column>
          <el-table-column prop="projectName" label="所属项目">
          </el-table-column>
          <el-table-column prop="userName" label="用户姓名"> </el-table-column>
          <el-table-column prop="userMobile" label="联系电话">
          </el-table-column>
          <el-table-column prop="tenantName" label="所属渠道">
          </el-table-column>
          <el-table-column prop="companyName" label="所属单位">
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSNForm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTenantList } from "@/api/org/channel";
import {
  getTenantList as getProjectList,
  getTenant as getProjectInfo,
} from "@/api/items/index";
import { deleteTenant, getSN, } from "@/api/order/index";
import {
  createTenant,
  updateTenant,
  getTenant,
  getTenantList as getSnCodesList,
  exportSample,
  getTenantPage,
  importTemplate,
  receiveTenant,
} from "@/api/specimen/index";
import { listSimpleMenus } from "@/api/system/menu";
import { getAccessToken } from "@/utils/auth";

export default {
  name: "TenantPackage",
  components: {},
  data() {
    return {
      //样本回收
      tableData: [],
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/admin-api/system/sample/import", // 请求地址
        headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
        data: {}, // 上传的额外数据，用于文件名
      },
      activeName: "bind",
      // 日期范围
      dateRange: [],
      testTypeDictData: [
        { label: "未发货", value: "to_deliver" },
        { label: "已发货", value: "delivered" },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户套餐列表
      list: [],
      // 弹出层标题
      title: "",
      titleSN: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        tenantName: undefined,
        snCode: undefined,
        userName: undefined,
        beginCreateTime: undefined,
      },
      // 表单参数
      form: { type: 1 },
      formData: {},
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      defaultProps: {
        label: "name",
        children: "children",
      },
      menuOptions: [], // 菜单列表
      // 表单校验
      rules: {
        tenantId: [
          {
            required: true,
            message: "请选择所属渠道",
            trigger: "change",
          },
        ],
        userName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        userMobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern:
              /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: "支持11位手机号码",
            trigger: "blur",
          },
        ],
        userId: [
          {
            required: true,
            message: "请输入身份证号",
            trigger: "blur",
          },
          // {
          //   pattern:
          //     /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}{0-9Xx}$/,
          //   message: "请输入正确的身份证号",
          //   trigger: "blur",
          // },
        ],
        projectId: [
          {
            required: true,
            message: "请选择所属项目",
            trigger: "change",
          },
        ],
        snCode: [
          {
            required: true,
            message: "请输入SN码",
            trigger: "blur",
          },
        ],
        userNation: [
          {
            required: true,
            message: "请输入民族",
            trigger: "blur",
          },
        ],
      },
      formRules: {
        tenantId: [
          {
            required: true,
            message: "请选择渠道名称",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入订单号",
            trigger: "blur",
          },
        ],
        projectId: [
          {
            required: true,
            message: "请选择所属项目",
            trigger: "change",
          },
        ],
        snBatchCode: [
          {
            required: true,
            message: "请选择产品批次",
            trigger: "change",
          },
        ],
        snCodes: [
          {
            required: true,
            message: "请输入SN码",
            trigger: "blur",
          },
        ],
        expireTime: [
          {
            required: true,
            message: "请选择有效期至",
            trigger: "change",
          },
        ],
      },
      payTypeOptions: [
        {
          label: "货到付款",
          value: "delivery",
        },
        {
          label: "月结",
          value: "monthly",
        },
      ],
      projectIdOptions: [],
      tenantIdOptions: [],
      discountPrice: "",
      //SN
      openSN: false,
      snBatchCodeOptions: [],
    };
  },
  watch: {
    "form.snNum": function (val) {
      if (this.form.isDiscount) {
        this.form.totalPrice =
          (val && parseFloat(this.form.discountPrice * val).toFixed(2)) || 0;
      } else {
        this.form.totalPrice =
          (val && parseFloat(this.form.price * val).toFixed(2)) || 0;
      }
    },
  },
  created() {
    this.getMenus();
    this.getProject();
    this.getTenant();
  },
  mounted() {
    const { tenantName } = this.$route.query
    console.log(tenantName, 666)
    if(tenantName){
      this.queryParams.tenantName = tenantName
    }
    this.getList();
  },
  methods: {
    searchSN() {
      const snCodes = this.formData.snCodes.trim();
      getSnCodesList({ snCodes: snCodes }).then((response) => {
        this.tableData = response.data || [];
      });
    },
    /** 新增按钮操作 */
    handleUpload() {
      this.upload.open = true;
      this.upload.title = "上传文件";
    },
    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {},
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true; // 禁止修改
    },
    /** 发起文件上传 */
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      // 清理
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 提示成功，并刷新
      this.$modal.msgSuccess("上传成功");
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.$download.excel(response, "样本录入模板.xls");
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    changeBatch() {
      this.formData.snCodes = "";
      this.setExpireTime();
    },
    //根据产品批次获取对应的过期时间
    setExpireTime() {
      const temp = this.snBatchCodeOptions.filter(
        (item) => item.code == this.formData.snBatchCode
      );
      const time = temp.length && temp[0].expireTime;
      if (time) {
        this.formData.expireTime = this.parseTime(time);
      }
    },
    getSNList(code) {
      getSN({ orderId: code }).then((response) => {
        this.snBatchCodeOptions = response.data || [];
      });
    },
    changeDiscount() {
      this.form.price = this.discountPrice;
    },
    changeProject() {
      getProjectInfo(this.form.projectId).then((response) => {
        const { price, discountPrice } = response.data;
        this.form.price = price;
        this.discountPrice = discountPrice;
      });
    },
    getTenant() {
      getTenantList({
        type: "agent",
        status: 0,
      }).then((response) => {
        this.tenantIdOptions = response.data || [];
      });
    },
    getProject() {
      getProjectList().then((response) => {
        this.projectIdOptions = response.data || [];
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      params.beginCreateTime = this.parseTime(this.queryParams.beginCreateTime);
      // 执行查询
      getTenantPage(params).then((response) => {
        this.list = response.data.list || [];
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    close() {
      this.openSN = false;
      this.resetSN();
    },
    /** 表单重置 */
    reset() {
      // 表单重置
      this.form = {
        id: undefined,
        tenantId: undefined,
        userName: undefined,
        snCode: undefined,
        userMobile: undefined,
        projectId: undefined,
        userNation: undefined,
        type: 1,
      };
      this.resetForm("form");
    },
    resetSN() {
      // 表单重置
      this.formData = {
        orderId: undefined,
        snBatchCode: undefined,
        snCodes: undefined,
      };
      this.resetForm("formData");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      // 表单重置
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "样本录入";
      // 设置为非严格，继续使用半选中
      this.menuCheckStrictly = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.open = true;
      this.title = "编辑";
      // 获得菜单列表
      getTenant(id).then((response) => {
        this.form = response.data;
        const { discountPrice } = response.data;
        this.discountPrice = discountPrice;
      });
    },
    /** 样本回收操作 */
    handleSN() {
      this.resetSN();
      this.openSN = true;
      this.titleSN = "样本录入";
      this.activeName = "bind";
    },
    /** 获得菜单 */
    getMenus() {
      listSimpleMenus().then((response) => {
        // 处理 menuOptions 参数
        this.menuOptions = [];
        // 只需要配置
        this.menuOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        this.form.discountPrice = this.form.price;
        if (this.form.id != null) {
          updateTenant({
            ...this.form,
            // menuIds: [...this.$refs.menu.getCheckedKeys(), ...this.$refs.menu.getHalfCheckedKeys()]
          }).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createTenant({
          ...this.form,
          // menuIds: [...this.$refs.menu.getCheckedKeys(), ...this.$refs.menu.getHalfCheckedKeys()]
        }).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 样本回收 提交按钮 */
    submitSNForm() {
      this.$refs["formData"].validate((valid) => {
        if (!valid) {
          return;
        }
        receiveTenant(this.formData).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.openSN = false;
            this.getList();
          });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteTenant(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = value;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出样本项?")
        .then(() => {
          this.exportLoading = true;
          return exportSample(queryParams);
        })
        .then((response) => {
          this.$download.excel(response, "样本管理.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.discount {
  position: relative;
}
.discount .el-button {
  position: absolute;
  top: 4px;
  right: -16px;
}
</style>
